<!-- 选择科室角色 -->
<template>
    <dy-dialog :title="title" ref="dialog" width="60%" @submitHandle="submitHandle">
        <div class="detababox1" v-loading="loading">
            <div class="babox1">
                <div class="baboxspan">
                    <span>已选科室-角色：</span>
                    <el-tooltip class="box-item" effect="dark" :content="selecttitle" placement="top-start"
                        v-if="selecttitle">
                        <span style="color:#1f2d3d;">{{ selecttitle }}</span>
                    </el-tooltip>
                </div>
                <div class="delectall" @click="delectallfun">
                    <el-icon>
                        <Close />
                    </el-icon>
                </div>
            </div>
            <div class="babox2">
                <!-- 科室信息 -->
                <div class="babox3">
                    <div>
                        <el-input size="default" clearable placeholder="科室" style="width: 240px;" :prefix-icon="Search"
                            v-model="searchinput">
                        </el-input>
                    </div>
                    <!-- {{departmentArr}} -->
                    <div class="boxfafk1">
                        <el-tree ref="tree" :data="departmentArr" node-key="id" default-expand-all :props="defaultProps"
                            :filter-node-method="filterNode" :expand-on-click-node="false" :default-checked-keys="[1]"
                            @node-click="handleNodeClick">
                            <template class="custom-tree-node" #default="{ node, data }">
                                <span v-if="data.department_name.length <= 10">{{ data.department_name }}</span>
                                <el-tooltip class="box-item" effect="dark" :content="data.department_name"
                                    placement="top-start" v-if="data.department_name.length > 10">
                                    <span>{{ data.department_name.substring(0, 10) + '...' }}</span>
                                </el-tooltip>
                            </template>
                        </el-tree>
                    </div>
                </div>
                <!-- 科室信息 -->
                <!-- 角色信息 -->
                <div class="babox4" style="padding-right: 20px;">
                    <div class="babox5">
                        <div>
                            <el-input size="default" class="elinput" clearable @keyup.enter.native="conditionalQuery"
                                @clear='conditionalQuery' :prefix-icon="Search" v-model="searchBox.role_name"
                                placeholder="角色名称"></el-input>
                        </div>
                        <div style="margin-left: 10px;">
                            <el-button type="primary" size="default" style="margin-right: -2px;" :icon="Search"
                                @click="conditionalQuery">查询</el-button>
                        </div>
                    </div>
                    <div class="babox6">
                        <el-table highlight-current-row height="218" :data="tableData" size="default"
                            ref="multipleTable" stripe :border="true"
                            style="width: 100%;border: 1px solid rgba(224, 230, 237, 1);" @row-click="changeTable"
                            @select="selectTable" @select-all="handleSelectionall">
                            <el-table-column type="selection" width="40">
                            </el-table-column>
                            <el-table-column prop="role_name" label="角色名称"></el-table-column>
                            <el-table-column prop="description" label="描述"></el-table-column>
                            <el-table-column prop="remark" label="备注"></el-table-column>
                        </el-table>
                        <div class="pagination">
                            <el-pagination background @size-change="gettabledata" @current-change="gettabledata"
                                :current-page.sync="currentPage" :page-size.sync="count" layout="total, sizes, pager"
                                :total="allcount"></el-pagination>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </dy-dialog>
</template>

<script setup>
import { ref, reactive, toRefs, watch } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import commonV from '@/common'
import api from '@/api'

const emits = defineEmits(['submitHandle'])

//数据
let state = reactive({
    title: '选择科室角色',
    loading: false,
    selecttitle: '',
    searchinput: '',
    selectedList: [],
    tableData: [],
    currentPage: 1, //第几页
    count: 10, //每页行数
    allcount: 1, //总数量
    departmentArr: [],
    departmentOinginData: [],
    defaultProps: {
        children: "children",
        label: "department_name"
    },
    //搜索框
    searchBox: {
        role_name: '',
        current_depart: null, //当前科室
        search: '',
    },
})
let {
    title, loading,
    selecttitle, searchinput,
    tableData, departmentArr,
    defaultProps, searchBox,
    currentPage, count, allcount
} = toRefs(state)

//log实例
let dialog = ref(null)
//table实例
let multipleTable = ref(null)
//tree实例
let tree = ref(null)

//监听科室搜索
watch(() => state.searchinput, (newVal) => {
    tree.value.filter(newVal)
})

//监听选中项给title赋值
watch(() => state.selectedList, () => {
    changeselecttitle()
}, { deep: true })

//删除选中项
let delectallfun = () => {
    state.selecttitle = ""
    multipleTable.value.clearSelection()
    state.selectedList = []
}

//改变选择
let changeselecttitle = () => {
    state.selecttitle = ""
    for (var i = 0; i < state.selectedList.length; i++) {
        let ccc = (i == state.selectedList.length - 1) ? "" : ","
        state.selecttitle += state.selectedList[i].department_name + ccc
    }
}

//编辑页面角色修改打开执行
let openFunction = (row) => {
    if (row == null || row.departmentRoles == null) {
        delectallfun() //清空
    } else {
        let departmentRoles = row.departmentRoles
        state.selecttitle = commonV.departroleformat(departmentRoles)
        for (let index = 0; index < departmentRoles.length; index++) {
            departmentRoles[index].department_name = departmentRoles[index].department_role + '_' + departmentRoles[
                index].role_name
        }
        state.selectedList = departmentRoles
    }
    getdepartdata()
}

//创建页面角色修改打开执行
let openFunction2 = (row) => {
    if (!row) {
        delectallfun() //清空
    } else {
        row = JSON.parse(JSON.stringify(row))
        for (let index = 0; index < row.length; index++) {
            const element = row[index];
            state.selecttitle += element.department_name + (index == (row.length - 1) ? '' : ',')
        }
        state.selectedList = row
    }
    getdepartdata()
}

//获取科室列表
let getdepartdata = async () => {
    console.log(state.departmentArr, '-=-=')
    state.loading = true
    let params = {}
    if (state.searchinput != '') {
        params.department_name = state.searchinput
    }
    let res = await api.getaxiosdata('department', params)
    if (res) {
        state.departmentOinginData = res
        state.departmentArr = commonV.transDatatotree(res, "id", "parent_id", "children") //将普通数组转换为tree数组
        tree.value.setCurrentKey(res[0].id)
        state.searchBox.current_depart = res[0]
        gettabledata()
    }
    state.loading = false
}

//过滤结构树
let filterNode = (value, data, node) => {
    if (!value) {
        return true
    }
    let _array = [] //这里使用数组存储 只是为了存储值。
    getReturnNode(node, _array, value)
    let result = false
    _array.forEach((item) => {
        result = result || item
    });
    return result
}

//获取返回节点的数据
let getReturnNode = (node, _array, value) => {
    let isPass = node.data && node.data.department_name && node.data.department_name.indexOf(value) !== -1
    isPass ? _array.push(isPass) : ''
    if (!isPass && node.level != 1 && node.parent) {
        getReturnNode(node.parent, _array, value)
    }
}

//科室节点点击
let handleNodeClick = (data) => {
    state.searchBox.current_depart = data
    gettabledata() //获取角色信息
}

//获取角色信息
let gettabledata = async () => {
    state.loading = true
    let params = {}
    if (state.searchBox.current_depart != "null") {
        params.department = state.searchBox.current_depart?.id
    }
    params.role_name = state.searchBox.role_name
    params.search = state.searchBox.search
    params.p = state.currentPage
    params.page_size = state.count
    let res = await api.getaxiosdata('roles', params)
    if (res) {
        state.tableData = res.results
        state.allcount = res.count
        state.loading = false
        nextTick(() => {
            try {
                for (var i = 0; i < state.selectedList.length; i++) {
                    for (var j = 0; j < state.tableData.length; j++) {
                        if (state.tableData[j].id == state.selectedList[i].id) {
                            multipleTable.value.toggleRowSelection(state.tableData[j])
                        }
                    }
                }
            } catch (e) { }
        })
    }
    state.loading = false
}

let conditionalQuery = () => {
    state.currentPage = 1
    state.count = 10
    gettabledata()
}

//当某一行被点击时会触发该事件
let changeTable = (row) => {
    let selected = true
    for (let index = 0; index < state.selectedList.length; index++) {
        const element = state.selectedList[index]
        if (element.id == row.id) {
            state.selectedList.splice(index, 1)
            selected = false
        }
    }
    if (selected) {
        row.department = state.searchBox.current_depart
        row.department_name = getdepartName(state.searchBox.current_depart, row.role_name)
        state.selectedList.push(row)
    }
    multipleTable.value.toggleRowSelection(row)
}

//获取科室全名称
let getdepartName = (depart, role_name) => {
    let name = depart.department_name
    if (depart.parent_id != null) {
        let row = state.departmentOinginData.find(item => depart.parent_id == (item.id).toString())
        if (row != 'undefined') {
            name = row.department_name + "-" + name
        }
        while (row != 'undefined' && row.parent_id != null) {
            row = state.departmentOinginData.find(item => row.parent_id == (item.id).toString())
            name = row.department_name + "-" + name
        }
    }
    name = name + '-' + role_name
    return name
}

//当用户手动勾选数据行的 Checkbox 时触发的事件
let selectTable = (selection, row) => {
    let selected = selection.length && selection.indexOf(row) !== -1
    // true就是选中，0或者false是取消选中
    if (selected == true) {
        row.department_name = getdepartName(state.searchBox.current_depart, row.role_name)
        state.selectedList.push(row)
    } else {
        for (let index = 0; index < state.selectedList.length; index++) {
            const element = state.selectedList[index];
            if (element.id == row.id) {
                state.selectedList.splice(index, 1)
            }
        }
    }
}

//全选时触发的事件     
let handleSelectionall = (v) => {
    if (v.length != 0) {
        //全选加入
        for (let index = 0; index < v.length; index++) {
            const element = v[index]
            let select = false
            for (let i = 0; i < state.selectedList.length; i++) {
                if (element.id == state.selectedList[i].id) {
                    select = true
                }
            }
            if (!select) {
                element.department_name = getdepartName(state.searchBox.current_depart, element.role_name)
                state.selectedList.push(element)
            }
        }
    } else {
        for (let index = state.selectedList.length - 1; index >= 0; index--) {
            const element = state.selectedList[index];
            for (let i = 0; i < state.tableData.length; i++) {
                if (element.id == state.tableData[i].id) {
                    state.selectedList.splice(index, 1)
                }
            }
        }
    }
}

//确定
let submitHandle = () => {
    if (!state.selecttitle) {
        ElMessage({
            message: '未选择角色',
            type: 'warning'
        })
        return
    }
    emits('submitHandle', state.selecttitle, state.selectedList)
    dialog.value.handleClose()
}

defineExpose({ openFunction, openFunction2 })
</script>

<style lang="scss" scoped>
.detababox1 {
    width: 100%;
    padding-bottom: 10px;
    background: rgba(255, 255, 255, 1);
    border-radius: 2px;
    border: 1px solid rgba(211, 220, 230, 1);
}

.babox1 {
    font-size: 14px;
    color: rgba(132, 146, 166, 1);
    padding: 7px 10px;
    display: flex;
    justify-content: space-between;
    overflow: hidden;
    border-bottom: 1px solid #e0e6ed;
}

.baboxspan {
    width: 100%;
    /*超出部分隐藏*/
    overflow: hidden;
    /*超出部分文字以...显示*/
    text-overflow: ellipsis;
    /*不换行*/
    white-space: nowrap;
    cursor: pointer;
}

.babox4 {
    width: calc(100% - 250px);
}

.delectall {
    cursor: pointer;
    display: flex;
    align-items: center;
}

.delectall:hover {
    color: blue;
}

.babox2 {
    display: flex;
    margin-top: 10px;
}

.babox3 {
    margin: 0 10px;

    &:deep(.el-input__inner) {
        border-bottom: none;
        border-radius: 0;
    }

    &:deep(.el-input__prefix) {
        height: 8%
    }
}

.babox5 {
    display: flex;
    justify-content: space-between;
}

.babox6 {
    margin-top: 10px;
}

.elinput {
    width: 140px;
}

.pagination {
    margin-top: 20px;
    height: 30px;
    display: flex;
    justify-content: flex-end;
}

.boxfafk1 {
    width: 240px;
    height: 280px;
    border: 1px solid rgba(211, 220, 230, 1);
    overflow: auto;
    padding-bottom: 10px;
}

.boxfafk1 {
    &:deep(.el-tree-node.is-current>.el-tree-node__content) {
        background-color: #20a0ff !important;
        color: #ffffff;
    }
}

::-webkit-scrollbar {
    width: 5px;
    height: 6px;
    background-color: #F5F5F5;
}

::-webkit-scrollbar-track {
    -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
    border-radius: 10px;
    background-color: #FFF;
}

/*定义滑块 内阴影+圆角*/
::-webkit-scrollbar-thumb {
    border-radius: 8px;
    -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, .3);
    background-color: #AAA;
}

.babox6 {
    &:deep(.el-table__body tr.current-row>td) {
        background-color: #DEE4E8 !important;
    }
}
</style>